<?php

class coreHelper extends helperBase {
	var $jsTagOpened = false;
	
	function redirect($url, $status = '303') {
		if($this->aether->getMode()==AETHER_WEB) { //If web, redirect
			session_write_close(); //Make sure session data is being saved
			if(!isset($url[0])||(isset($url[0])&&$url[0]!='/')) {
				$url = $this->aether->config->get('general', 'webRoot') . $url;
			}
			header('Location: '.$url, true, $status); //Go!
		} else {
			return false;
		}
	}

	function redeclare($url) { //Similar to redirect, but it doesn't actually do an HTTP redirect, just redeclares the aether object
		new aether($url, $this->aether->getMode());
		exit;
	}

	function getUrl() {
		return $this->aether->config->get('general', 'webRoot') . $this->aether->getRawUrl();
	}

	function processArgs() { //Process the PHP CLI arguments into a nice array
		if($this->aether->getMode()==AETHER_CLI&&$this->aether->controller->getParam('args')) { //Make sure its in CLI mode and that there are params to process
			$args = array();
			$argsArray = explode('-',$this->aether->controller->getParam('args').'/');
			foreach($argsArray as $arg) {
				$name = substr($arg,0,1);
				$values = explode('/',substr($arg,2,strlen($arg)-3));
				$args[$name] = $values;
			}
			$this->aether->controller->setParam('args', $args);
		} else
			$this->aether->controller->setParam('args', array());
	}
	
	function triggerJsFunction($name, $args = array()) {
		$this->aether->controller->view = false;
		if(!$this->jsTagOpened) {
			$this->jsTagOpened = true;
			echo '<script type="text/javascript"><!--';
		}
		echo NL.$name.'(';
		$first = true;
		if(!is_array($args)) {
			$args = array($args);	
		}
		foreach($args as $arg) {
			if($first) {
				$first = false;
			} else {
				echo ', ';
			}
			if(is_int($arg)) {
				echo $arg;
			}
			if(is_string($arg)) {
				echo '"'.$arg.'"';
			}
		}
		echo ');'.NL;
	}
	
	function closeJsTag() {
		if($this->jsTagOpened) {
			echo '--></script>';
			$this->jsTagOpened = false;
		}
	}
}
